package com.jasperframework.boot.common.utils;

import cn.hutool.http.ContentType;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jasperframework.boot.common.exception.ApplicationRuntimeException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.stream.Collectors;

/**
  * <p> 用于获取请求相关信息的工具类 </p>
  *
  * @site https://miliqkdoc.motopa.cn/
  * @author daizhao
  * @date 2022/12/12 12:12
  */
@Slf4j
public class HttpRequestUtil {

    public static String getUserAgent(HttpServletRequest request) {
        return request.getHeader("User-Agent");
    }

    /**
     * <p>获取请求参数 </p>
     * @param request
     * @date:  22:35 2023/6/1
     * @return: java.lang.Object
     * @author: tuonioooo
     */
    public static String getAllReqParams(HttpServletRequest request) throws IOException {
        return isArray(request)
                ? reqParam2JSONArray(request).toJSONString()
                : reqParam2JSON(request).toString();
    }

    /**
     * 获取Body请求体参数
     * @param request
     * @return String
     */
    public static String getBodyString(HttpServletRequest request){
        StringBuilder body = new StringBuilder();
        if(isConvertJSON(request)){
            try {
                String str;
                while((str = request.getReader().readLine()) != null){
                    body.append(str);
                }
                return body.toString();
            } catch (Exception e) {
                throw new ApplicationRuntimeException("获取body请求体参数异常");
            }
        }
        return body.toString();
    }

    /**
     * <p> 获取Body请求体参数 并转换为JSONArray格式 </p>
     * @param request
     * @date:  22:26 2023/6/1
     * @return: com.alibaba.fastjson.JSONArray
     * @author: daizhao
     */
    public static JSONArray reqParam2JSONArray(HttpServletRequest request) throws IOException {
        if (isArray(request)) {
            return JSONArray.parseArray(request.getReader().lines().collect(Collectors.joining("")));
        }
        return new JSONArray();
    }

    /**
     * 获取Body请求体 + query string参数 并转换为JSON格式
     * @param request
     * @return
     */
    public static JSONObject reqParam2JSON(HttpServletRequest request) {
        JSONObject returnObject = new JSONObject();
        if(isConvertJSON(request)){
            String body = "";
            try {
                body=request.getReader().lines().collect(Collectors.joining(""));
                if(StringUtils.isEmpty(body)) {
                    return returnObject;
                }
                return JSONObject.parseObject(body);
            } catch (Exception e) {
                log.error("请求参数转换异常 = {}", e);
                throw new ApplicationRuntimeException("请求参数转换异常");
            }
        }

        // 参数Map
        Map properties = request.getParameterMap();

        // 返回值Map
        Iterator entries = properties.entrySet().iterator();
        Map.Entry entry;
        String name;
        String value = "";
        while (entries.hasNext()) {
            entry = (Map.Entry) entries.next();
            name = (String) entry.getKey();
            Object valueObj = entry.getValue();
            if(null == valueObj){
                value = "";
            }else if(valueObj instanceof String[]){
                String[] values = (String[])valueObj;
                for(int i=0;i<values.length;i++){
                    value = values[i] + ",";
                }
                value = value.substring(0, value.length()-1);
            }else{
                value = valueObj.toString();
            }

            if(!name.contains("[")){
                returnObject.put(name, value);
                continue;
            }
            //添加对json对象解析的支持  example: {ps[abc] : 1}
            String mainKey = name.substring(0, name.indexOf("["));
            String subKey = name.substring(name.indexOf("[") + 1 , name.indexOf("]"));
            JSONObject subJson = new JSONObject();
            if(returnObject.get(mainKey) != null) {
                subJson = (JSONObject)returnObject.get(mainKey);
            }
            subJson.put(subKey, value);
            returnObject.put(mainKey, subJson);
        }
        return returnObject;

    }

    /**
     * 判断请求参数是否转换为json格式
     * @param request
     * @return
     */
    private static boolean isConvertJSON(HttpServletRequest request){
        String contentType = request.getContentType();
        //有contentType  && json格式，  get请求不转换
        //application/json 需要转换为json格式
        return contentType != null
                && contentType.toLowerCase().indexOf(ContentType.JSON.getValue()) >= 0
                && !request.getMethod().equalsIgnoreCase("GET");
    }

    /**
     * <p>判断请求体是否是数组格式</p>
     * @param request
     * @date:  22:40 2023/6/1
     * @return: boolean
     * @author: daizhao
     */
    private static boolean isArray(HttpServletRequest request) throws IOException {
        if (isConvertJSON(request)) {
            String body = "";
            body = request.getReader().lines().collect(Collectors.joining(""));
            if (StringUtils.isEmpty(body)) { //如果请求体body 为空 直接返回空数组
                return false;
            }
            if(JSONUtil.isJsonArray(body)){
                return true;
            }
        }
        return false;
    }

    /**
     * 获取所有请求的头部信息
     * @param request
     * @return
     */
    public static Map<String, String> getHeaders(HttpServletRequest request) {
        Map<String, String> map = new HashMap<String, String>();
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            map.put(key, value);
        }
        return map;
    }

    /**
     * 获取客户端类型
     * @param request
     * @return
     */
    public static String getClientType(HttpServletRequest request){
        String agent = request.getHeader("User-Agent").toLowerCase();
        if(agent.indexOf("android") > -1){
            return "android";
        }else if (agent.indexOf("ipad") > -1 || agent.indexOf("iphone") > -1
                || agent.indexOf("tablet") > -1){
            return "ios";
        }else {
            return "pc";
        }
    }

    /**
     * 获取Ip地址
     * @param request
     * @return
     */
    public static String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            //Weblogic集群下,程序获取客户端IP
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if (ip != null && ip.length() > 15) {
            if (ip.indexOf(",") > 0) {
                ip = ip.substring(0, ip.indexOf(","));
            }
        }
        if (ip!=null && ip.equalsIgnoreCase("0:0:0:0:0:0:0:1")) {
            // 客户端和服务端在同一台机器上，会显示次ip地址
            ip = "127.0.0.1";
        }
        return ip;
    }
}
